<template>
  <div class="freezedataform">
    <div class="form-wrap">
      <el-card style="margin: 6px">
        <div class="menu-wrap">
          <el-input
            v-model="deptName"
            :placeholder="$t('device.device-linkage.188958-0')"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px; margin-right: 10px"
          />
          <el-tree
            :default-expanded-keys="[100]"
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-card>
      <el-card style="margin: 6px 6px 0 6px">
        <div style="height: 380px" class="deviceTable">
          <!-- <el-tabs v-model="activeName1" @tab-click="handleClick">
            <el-tab-pane
              :label="$t('device.device-linkage.188958-1')"
              name="first"
            ></el-tab-pane>
            <el-tab-pane
              :label="$t('device.device-linkage.188958-2')"
              name="second"
            ></el-tab-pane>
            <el-tab-pane
              :label="$t('device.device-linkage.188958-3')"
              name="third"
            ></el-tab-pane>
          </el-tabs> -->
          <el-input
            v-model="queryParams.serialNumber"
            :placeholder="$t('device.device-edit.148398-2')"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 10px; margin-right: 10px"
            @keydown.enter.native="getDeviceList"
          />
          <el-menu
            ref="elmenu"
            class="menu-wrap"
            style="margin-right: 10px; height: 335px"
            :default-openeds="['1']"
            :default-active="checkDevice"
          >
            <el-submenu index="1" style="margin-left: -5px">
              <template slot="title">
                <i class="el-icon-menu"></i>
                <span style="font-size: 14px; padding: 0"
                  >{{ $t("device.device-linkage.188958-5") }}(
                  {{ deviceList.length + "/" + total }} )</span
                >
              </template>
              <el-menu-item
                v-for="item in deviceList"
                :key="item.serialNumber"
                :index="item.serialNumber"
                class="custom-menu-item"
                @click="handleTypeClick(item)"
              >
                {{ item.deviceName }}
              </el-menu-item>
            </el-submenu>
          </el-menu>
          <el-pagination
            v-show="total > 0"
            :total="total"
            small
            :current-page.sync="queryParams.pageNum"
            :page-size="queryParams.pageSize"
            layout="prev, pager, next"
            @current-change="getDeviceList"
          ></el-pagination>
        </div>
      </el-card>
    </div>
    <!--冻结数据详细信息主题信息-->
    <div class="modal_body">
      <div class="rtu">
        <!--冻结数据条件过滤-->
        <div class="searchform" style="float: left; display: flex">
          <el-date-picker
            v-model="timeslot"
            type="daterange"
            align="right"
            size="mini"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            unlink-panels
            :range-separator="$t('tips.to')"
            :start-placeholder="$t('tips.startdate')"
            :end-placeholder="$t('tips.enddate')"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
          <div class="seleteProject">
            <span>{{$t('dataCenter.history.384934-14')}}：</span>
            <el-select
              v-model="chartType"
              multiple
              collapse-tags
              :placeholder="$t('dataCenter.history.384934-15')"
            >
              <el-option
                v-for="item in devIdentifierList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
        </div>
        <div class="searchform">
          <el-button
            class="el-button-amplify"
            size="mini"
            type="info"
            icon="el-icon-search"
            circle
            @click="refreshdata(search)"
          ></el-button>
        </div>
      </div>
      <div class="echart_btn">
        <el-button
          type="primary"
          plain
          icon="el-icon-s-data"
          size="mini"
          :class="checkBtn1"
          @click="showChart"
          >{{$t('dataCenter.history.384934-16')}}</el-button
        >
        <el-button
          type="primary"
          plain
          icon="el-icon-document"
          size="mini"
          :class="checkBtn2"
          @click="showData"
          >{{$t('dataCenter.history.384934-17')}}</el-button
        >
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          :class="checkBtn3"
          @click="exportExcel"
          >{{$t('dataCenter.history.384934-18')}}</el-button
        >
      </div>
      <div class="clear"></div>
      <div v-show="checkBtn1 == 'checkBtn'" v-loading="loading">
        <div
          v-show="devDatas.length !== 0"
          ref="devLineChart"
          style="width: 100%; height: 720px; background: #fff"
        ></div>
        <div class="notdata" style="width: 100%; height: 720px; background: #fff">
          {{$t('dataCenter.history.384934-12')}}
        </div>
      </div>
      <div
        v-show="checkBtn2 == 'checkBtn'"
        v-loading="loading"
        class="data_table"
      >
        <el-table
          style="margin-top: 50px"
          :data="devTableList"
          :border="false"
          height="620px"
        >
          <el-table-column
            :label="$t('dataCenter.history.384934-13')"
            prop="time"
            width="200"
          />
          <el-table-column
            v-for="item in devTableHeaderTemp"
            :key="item.value"
            :label="item.name"
            :prop="item.value"
          />
        </el-table>
        <el-pagination
          layout="total,sizes, prev, pager, next, jumper"
          :page-sizes="[12, 50, 100, 300]"
          :total="devTotal"
          :current-page.sync="devPageNum"
          :page-size="devPageSize"
          @pagination="getDevTableList"
          @size-change="handleSizeChange"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { getElectricalparameterLogList } from "@/api/iot/log";
import LampFreezedatatunnel from "@/components/echarts/lampfreezedatatunnel";
import LampFreezedatadimmer from "@/components/echarts/lampfreezedatadimmer";
import { deptsTreeSelect, getDataCenterDeviceHistory } from "@/api/iot/device";
import { listDeviceShort } from "@/api/iot/device";
export default {
  props: {
    productList: {
      type: Array,
      default: [],
    },
  },
  components: {
    LampFreezedatatunnel,
    LampFreezedatadimmer,
  },
  name: "freezedataform",
  data() {
    return {
      currentPage: 1,
      perpage: 15,
      total: 0,
      devTotal: 0,
      tableData: [],
      starttime: "",
      endtime: "",
      pickerOptions: {
        // 设置不能选择的日期
        onPick: ({ maxDate, minDate }) => {
          this.choiceDate0 = minDate.getTime();
          if (maxDate) {
            this.choiceDate0 = "";
          }
        },
        disabledDate: (time) => {
          let choiceDateTime = new Date(this.choiceDate0).getTime();
          const minTime = new Date(choiceDateTime).setMonth(
            new Date(choiceDateTime).getMonth() - 1
          );
          const maxTime = new Date(choiceDateTime).setMonth(
            new Date(choiceDateTime).getMonth() + 1
          );
          const min = minTime;
          const newDate =
            new Date(new Date().toLocaleDateString()).getTime() +
            24 * 60 * 60 * 1000 -
            1;
          const max = newDate < maxTime ? newDate : maxTime;
          //如果已经选中一个日期 则 返回 该日期前后一个月时间可选
          if (this.choiceDate0) {
            return time.getTime() < min || time.getTime() > max;
          }
          //若一个日期也没选中 则 返回 当前日期以前日期可选
          return time.getTime() > newDate;
        },
      },

      filtervalue: "",
      filtername: "",
      search: "",
      timeslot: "",
      productName: "",
      productId: "",
      lamp_echarttype: true,
      deptName: "",
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label",
      },
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        deptId: undefined,
        showChild: true,
        status: "",
        serialNumber: "",
      },
      activeName1: "first", // 当前激活的标签页
      deviceList: [],
      chartType: ["DRA_Power"],
      checkBtn1: "checkBtn",
      checkBtn2: "",
      checkBtn3:"checkBtn2",
      devIdentifierList: [
        { label: this.$t("title.tunnellightingsystem_statisticanalysis_title_activepower"), value: "DRA_Power" },
        { label: this.$t('title.tunnellightingsystem_systemmanagement_title_workingcurrent'), value: "DRA_Current" },
        { label: this.$t('title.tunnellightingsystem_systemmanagement_title_workingvoltage'), value: "DRA_Voltage" },
        { label: this.$t('tips.tunnellightingsystem_tunnelpanoramicview_tips_dimmingratio'), value: "DRA_Dim" },
        { label: this.$t('tips.tunnellightingsystem_tunnelpanoramicview_tips_colortemperatureratio'), value: "DRA_Color" },
        { label: this.$t('title.tunnellightingsystem_systemmanagement_title_worktemp'), value: "DRA_Temp" },
      ],
      loading: false,
      deviceInfo: {},
      devDatas: [],
      devTableComTemp: [], // 设备列表table数据
      devPageNum: 1,
      devPageSize: 12,
      devTableHeaderTemp: [],
      checkDevice: null,
    };
  },
  created() {
    this.getDeptTree();
    this.$nextTick(() => {
      this.getDeviceList();
    });
  },
  watch: {
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  computed: {
    devTableList() {
      const start = (this.devPageNum - 1) * this.devPageSize;
      const end = start + this.devPageSize;
      return this.devTableComTemp.slice(start, end);
    },
  },
  mounted() {
    //在模板编译完成后执行
    let that = this;
    this.productId = this.productList[0].productId;
    let queryParams = {
      pageNum: this.currentPage,
      pageSize: this.perpage,
      productId: this.productId,
    };
    this.inittimeslot();
  },
  methods: {
    //设置表头行的样式
    tableHeaderStyle({ row, column, rowIndex, columnIndex }) {
      return "background-color: #ffffff;color: #000000;font-size:14px";
    },
    //导出的方法
    exportExcel() {
      require.ensure([], () => {
        const { export_json_to_excel } = require("@/Excel/Export2Excel");

        // 上面设置Excel的表格第一行的标题
        const filterVal = this.devTableHeaderTemp.map((item) => item.value);
        filterVal.unshift("time");
        // 上面的index、nickName、name是tableData里对象的属性
        const list = this.devTableList; //把data里的tableData存到list
        const data = this.formatJson(filterVal, list);
        let tHeader = this.devTableHeaderTemp.map((item) => item.name);
        tHeader.unshift(this.$t("dataCenter.history.384934-13"));
        export_json_to_excel(tHeader, data, this.$t('title.freezingdata'));
      //   if (sessionStorage.lang === "zh-cn") {
      //     export_json_to_excel(tHeader, data, "系统日志");
      //   } else {
      //     export_json_to_excel(filterVal, data, "System Log");
      //   }
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    refreshdata(msg) {
      if (this.chartType.length == 0) {
        this.$message.error(this.$t("dataCenter.history.384934-19"));
        return;
      }
      if (this.timeslot == null || this.timeslot.length == 0) {
        this.$message.error(this.$t("dataCenter.history.384934-20"));
        return;
      }
      if (Object.keys(this.deviceInfo).length === 0) {
        this.$message.error(this.$t("dataCenter.history.384934-21"));
        return;
      }
      this.getDevChartDatas();
    },
    seleteProject() {
      this.refreshdata();
    },
    getFreezedataList(params) {
      let that = this;
      getElectricalparameterLogList(params).then((response) => {
        const newData = response.rows.map((item) => {
          item.groupid = null;
          return that.conversionData(item);
        });
        that.tableData = newData;
        that.total = response.total;
      });
    },
    conversionData(data) {
      const newList = {};
      for (let key in data) {
        newList[key] = data[key] == null || data[key] == "" ? "--" : data[key];
      }
      return newList;
    },
    DateTimeSlot() {
      if (this.timeslot == null) this.timeslot = "";
      this.starttime = this.timeslot[0];
      this.endtime = this.timeslot[1];
      if (this.starttime == null || this.starttime == "") {
        this.inittimeslot(); //初始化为近1个月操作日志
      }
    },
    inittimeslot() {
      //初始化为近1个月操作日志
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24);
      this.endtime = this.FormatDate(end, "yyyy-MM-dd") + " 23:59:59";
      this.starttime = this.FormatDate(start, "yyyy-MM-dd") + " 00:00:00";
      this.timeslot = [this.starttime, this.endtime];
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      if (data.groupId) {
        this.queryParams.groupId = data.groupId;
      } else {
        this.queryParams.groupId = null;
      }
      if (data.id == 0) {
        return;
      }
      this.queryParams.deptId = data.id;
      this.getDeviceList();
    },
    /** 查询机构下拉树结构 */
    getDeptTree() {
      deptsTreeSelect().then((response) => {
        this.deptOptions = this.replaceGroupChildrenWithChildren(response.data);
        this.queryParams.deptId = response.data[0].id;
      });
    },
    replaceGroupChildrenWithChildren(treeData) {
      return treeData.map((newNode) => {
        if (newNode.groupChildren && newNode.groupChildren.length > 0) {
          for (let i in newNode.groupChildren) {
            newNode.groupChildren[i].label = newNode.groupChildren[i].groupName;
          }
          let obj = {
            label: this.$t("device.device-edit.148398-83"),
            id: 0,
            children: newNode.groupChildren,
          };
          if (newNode.children && newNode.children.length > 0) {
            newNode.children.unshift(obj);
          } else {
            newNode.children = [obj];
          }
        }

        // 如果节点有 children，递归处理子节点
        if (newNode.children && newNode.children.length > 0) {
          this.replaceGroupChildrenWithChildren(newNode.children);
        }

        return newNode;
      });
    },
    getDeviceList() {
      // if (this.queryParams.deptId == undefined) {
      //     //默认机构
      //     this.queryParams.deptId = 100;
      // }
      listDeviceShort(this.queryParams).then((response) => {
        this.deviceList = response.rows;
        this.deviceInfo = response.rows[0];
        this.checkDevice = response.rows[0].serialNumber;
        this.refreshdata();
        if (this.deviceId === 0) {
          this.deviceId = this.deviceList[0].deviceId;
        }
        this.total = response.total;
      });
    },
    handleClick(tab, event) {
      // 点击标签页的逻辑处理
      if (tab.name === "first") {
        //全部包括在线，离线，未激活和禁用状态
        this.queryParams.status = "";
        this.getDeviceList();
      } else if (tab.name === "second") {
        this.queryParams.status = 3;
        this.getDeviceList();
      } else if (tab.name === "third") {
        this.queryParams.status = 4;
        this.getDeviceList();
      }
    },
    showChart() {
      this.checkBtn1 = "checkBtn";
      this.checkBtn2 = "";
      console.log(this.chartType);
    },
    showData() {
      this.checkBtn1 = "";
      this.checkBtn2 = "checkBtn";
    },
    drawDevLine() {
      // 初始化折线图
      this.charts = this.$echarts.init(this.$refs.devLineChart);
      this.charts.clear();
      // 设置折线图数据和样式
      this.charts.setOption({
        tooltip: {
          trigger: "axis",
        },
        legend: {
          align: "right",
          left: "3%",
          top: "15%",
        },
        grid: {
          top: "20%",
          left: "10%",
          right: "12%",
          bottom: "8%",
          containLabel: true,
        },
        toolbox: {
          feature: {
            dataView: {},
            restore: {},
            saveAsImage: {},
          },
        },
        dataZoom: [
          {
            type: "inside",
            start: 0,
            end: 100,
          },
          {
            start: 0,
            end: 100,
          },
        ],
        // 自定义：设置x轴刻度
        xAxis: {
          type: "category",
          boundaryGap: true,
          axisTick: {
            alignWithLabel: true,
          },
          // 自定义标签
          data:
            this.devDatas.length !== 0 &&
            this.devDatas.map((item) => Object.keys(item)[0]),
        },
        // 自定义：设置y轴刻度
        yAxis: {
          type: "value",
          scale: true, //自适应
        },
        // 设置数据
        series: this.getDevSeries(),
      });
    },
    getDevChartDatas() {
      this.loading = true;
      let identifierList = [];
      for (let i in this.chartType) {
        let obj = {};
        obj.identifier = this.chartType[i];
        obj.type = 1;
        identifierList.push(obj);
      }
      const params = {
        deviceId: this.deviceInfo.deviceId,
        serialNumber: this.deviceInfo.serialNumber,
        identifierList: identifierList,
        beginTime: this.timeslot[0],
        endTime: this.timeslot[1],
      };
      getDataCenterDeviceHistory(params).then((res) => {
        if (res.code === 200) {
          this.devDatas = res.data;
          this.formatDevTableDatas();
          if (this.devDatas.length !== 0) {
            setTimeout(() => {
              this.drawDevLine();
            }, 500);
          }
        }
        this.loading = false;
      });
    },
    // 获取设备的series
    getDevSeries() {
      return this.chartType.map((item) => {
        return {
          name: this.devIdentifierList.find((chil) => chil.value === item)
            .label,
          type: "line",
          stack: this.$t("dataCenter.history.384934-23"),
          data: this.devDatas.map((d) => {
            const ide = Object.values(d)[0].find(
              (f) => Object.keys(f)[0] === item
            );
            return Object.values(ide)[0];
          }),
        };
      });
    },
    // 格式化设备列表数据
    formatDevTableDatas() {
      this.devTableComTemp = this.devDatas.map((item) => {
        const time = Object.keys(item)[0];
        let obj = {};
        Object.values(item)[0].forEach((chil) => {
          obj[Object.keys(chil)[0]] = Object.values(chil)[0];
        });
        return { time, ...obj };
      });
      this.devTotal = this.devDatas.length;
      this.devTableHeaderTemp = this.chartType.map((item) => {
        return {
          name: this.devIdentifierList.find((chil) => chil.value === item)
            .label,
          value: item,
        };
      });
    },
    handleTypeClick(item) {
      this.deviceInfo = item;
      if (this.chartType.length == 0) {
        this.$message.error(this.$t("dataCenter.history.384934-19"));
        return;
      }
      if (this.timeslot == null || this.timeslot.length == 0) {
        this.$message.error(this.$t('dataCenter.history.384934-20'));
        return;
      }
      this.getDevChartDatas();
    },
    getDevTableList(e) {
      this.devPageNum = e.page;
      this.devPageSize = e.limit;
    },
    handleSizeChange(val) {
      this.devPageSize = val;
    },
  },
};
</script>

<style scoped>
.freezedataform {
  display: flex;
  padding: 0px 10px;
  justify-content: space-around;
}
.form-wrap >>> .el-card__body {
  width: 312px;
}
.modal_body {
  width: 78%;
  margin-left: 2px;
}
.menu-wrap {
  margin-top: -5px;
  height: 345px;
  overflow-x: auto;
  overflow-y: auto;
  padding-left: 0 !important;
}
.echart_btn {
  margin: 5px 0px;
}
.checkBtn {
  background: #409eff;
  border-color: #409eff;
  color: #fff;
}
.checkBtn2{
  color: #409EFF !important;
  background: #ecf5ff !important;
  border-color: #b3d8ff !important;
}
.menu-wrap .el-submenu__title {
  padding-left: 0 !important;
}
.el-button-amplify {
  height: 28px;
  margin-left: 5px;
  float: left;
}
.export {
  position: absolute;
  right: 20px;
}
.rtutable {
  margin-top: 10px;
  border-radius: 5px;
  height: 470px;
}
.search {
  position: relative;
  float: left;
  margin-left: -200px;
}
.syslogbar {
  float: left;
  width: 350px;
  margin: auto 0px;
}
.rtutable >>> .el-table {
  background-color: #edeef0;
}
.subtable >>> .el-table__body-wrapper {
  background-color: #edeef0;
}
.subtable >>> .el-table__row {
  background-color: white;
  color: #000000;
}
.rtutable >>> .el-table td {
  padding: 4px 0;
  font-size: 12px;
  border-bottom: 0.1px solid #dddddd;
}
.rtutable >>> .el-table th.is-leaf {
  border-bottom: 0.1px solid #dddddd;
}
.subtable >>> .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #3586ff;
}
.subtable >>> .el-checkbox__inner::after {
  border: 2px solid #ffffff;
  border-left: 0px;
  border-top: 0px;
}

.clear {
  clear: both;
}
.rtutable >>> .el-table th.gutter {
  display: table-cell !important;
}
.searchform >>> .el-range-editor.el-input__inner {
  padding: 0px 10px;
}
.searchform >>> .el-range-editor--mini .el-range-separator {
  line-height: 26px;
}
.rtutable /deep/.el-table__body-wrapper {
  height: calc(100% - 50px) !important;
}
.seleteProject {
  margin-left: 10px;
}
.seleteProject >>> .el-input .el-input__inner {
  height: 28px !important;
  line-height: 28px;
}
.seleteProject >>> .el-input .el-input__icon {
  line-height: 28px;
}
.seleteProject >>> .el-select .el-select__tags > span {
  display: flex;
}
.overview_echart {
  width: 100%;
}
.overview_echart >>> .el-switch {
  margin: 10px 10px;
}
.data_table >>> .el-pagination {
  text-align: center;
  background-color: #fff;
  height: 50px;
  padding-top: 10px;
}
.notdata{
  color: #909399;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}
</style>
<style>
.freeSelect {
  min-width: 220px !important; /* 设置您需要的宽度 */
}
</style>
